﻿using Aribaccio.Security;
using BDPAutodetect.Client.ViewWindows.WindowDialog;
using BDPAutodetect.Mgrcore;
using BDPAutodetect.Models;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace BDPAutodetect.Client
{
    /// <summary>
    /// 用户角色设置管理视图模型类
    /// </summary>
    public partial class SettingUserRoleViewModel : BaseViewModel<UserControl>
    {
        /// <summary>
        /// 用户管理实例
        /// </summary>
        protected UserManager UserMgr { get; set; }
        /// <summary>
        /// 角色选择集
        /// </summary>
        [ObservableProperty]
        protected ObservableCollection<MRoleDto> roles;
        /// <summary>
        /// 用户数据集
        /// </summary>
        [ObservableProperty]
        protected ObservableCollection<MUserDto> userItems;

        /// <summary>
        /// 构造函数
        /// </summary>
        public SettingUserRoleViewModel(UserManager argUserManager)
        {
            this.UserMgr = argUserManager;
            this.Roles = new ObservableCollection<MRoleDto>();
            this.UserItems = new ObservableCollection<MUserDto>();
        }

        /// <summary>
        /// 初始化加载权限编辑
        /// </summary>
        /// <returns></returns>
        protected async Task InitLoadPermission()
        {
            if (this.PowerPermission == null) return;
            var resultTaskPowers = this.UserMgr.GetUserPowers(this.PowerPermission.Power.ID);
            await resultTaskPowers.ConfigureAwait(false);
            if (resultTaskPowers != null && resultTaskPowers.Result != null && resultTaskPowers.Result.Count > 0)
            {
                this.IsVisibilityPermission = Visibility.Visible;
            }
        }

        /// <summary>
        /// 页面初始化加载事件
        /// </summary>
        [RelayCommand]
        public async Task ExecuteLoaded()
        {
            if (this.IsLoaded) return;
            //获取编辑权限
            var resultTask = this.InitLoadPermission();
            await resultTask.ConfigureAwait(false);

            //标记初始化加载完成
            this.IsLoaded = true;
            //初始化查询数据
            resultTask = this.QueryData();
            await resultTask.ConfigureAwait(false);
        }

        /// <summary>
        /// 新增命令事件
        /// </summary>
        /// <returns></returns>
        [RelayCommand]
        public async Task ExecuteInsert()
        {
            this.IsExecutedIdle = false;
            try
            {
                //编辑弹出层
                SettingUserEditorDialog editorDialog = new SettingUserEditorDialog("用户添加", null, this.Roles);
                bool? bResult = editorDialog.ShowDialog();
                if (!bResult.HasValue || !bResult.Value) return;
                if (editorDialog.DialogResultData == null) return;

                var result = this.UserMgr.InsertUser(editorDialog.DialogResultData);
                await result.ConfigureAwait(false);
                if (result != null && result.Result != null)
                {
                    await Task.Factory.StartNew(() =>
                    {
                        this.UserItems.Add(result.Result);
                    }, new CancellationTokenSource().Token, TaskCreationOptions.None, base.syncContextTask);
                }
            }
            finally
            {
                this.IsExecutedIdle = true;
            }
        }

        /// <summary>
        /// 删除命令事件
        /// </summary>
        /// <returns></returns>
        [RelayCommand]
        public async Task ExecuteDelete(MUserDto argUserDto)
        {
            this.IsExecutedIdle = false;
            try
            {
                var result = this.UserMgr.DeleteUser(argUserDto);
                await result.ConfigureAwait(false);
                if (result != null && result.Result)
                {
                    await Task.Factory.StartNew(() =>
                    {
                        this.UserItems.Remove(argUserDto);
                    }, new CancellationTokenSource().Token, TaskCreationOptions.None, base.syncContextTask);
                }
                else
                {
                    MessageBox.Show("删除失败！", "警告", MessageBoxButton.OK);
                }
            }
            finally
            {
                this.IsExecutedIdle = true;
            }
        }

        /// <summary>
        /// 编辑命令事件
        /// </summary>
        /// <returns></returns>
        [RelayCommand]
        public async Task ExecuteEditor(MUserDto argUserDto)
        {
            this.IsExecutedIdle = false;
            try
            {
                //编辑弹出层
                SettingUserEditorDialog editorDialog = new SettingUserEditorDialog("用户编辑", argUserDto, this.Roles);
                bool? bResult = editorDialog.ShowDialog();
                if (!bResult.HasValue || !bResult.Value) return;
                if (editorDialog.DialogResultData == null) return;

                var result = this.UserMgr.UpdateUser(editorDialog.DialogResultData);
                await result.ConfigureAwait(false);
            }
            finally
            {
                this.IsExecutedIdle = true;
            }
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        protected async Task QueryData()
        {
            await Task.Factory.StartNew(() =>
            {
                try
                {                  
                    var roles = this.UserMgr.GetRoles();
                    if (this.Roles.Count <= 0 && roles != null && roles.Count > 0)
                    {
                        foreach (var itemRole in roles.OrderBy(v => v.ID))
                        {
                            this.Roles.Add(itemRole);
                        }

                    }

                    this.UserItems.Clear();
                    var users = this.UserMgr.GetUsers();
                    if (users != null && users.Count > 0)
                    {
                        foreach (var itemUser in users.OrderBy(v => v.ID))
                        {
                            this.UserItems.Add(itemUser);
                        }
                    }                   
                }
                finally
                {
                    this.IsExecutedIdle = true;
                }
            }, new CancellationTokenSource().Token, TaskCreationOptions.None, base.syncContextTask);
        }
    }
}
